package com.shuai.chatroom.controller;

import com.shuai.chatroom.common.*;
import com.shuai.chatroom.entity.UserInfo;
import com.shuai.chatroom.exception.ControllerException;
import com.shuai.chatroom.exception.MapperException;
import com.shuai.chatroom.service.FriendService;
import com.shuai.chatroom.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

@RestController
@ResponseBody
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private FriendService friendService;

    @PostMapping("/login")
    public HttpResult login(String username, String password, HttpServletRequest request, String captcha) throws ControllerException {
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            throw new ControllerException("登录信息填写不完整！");
        }
        //先验证看验证码输入正确没
        if (!MyCaptchaUtils.verifyCaptcha(request, captcha)) {
            return HttpResult.fail("验证码错误！");
        }
        UserInfo loginUser = userService.login(username);
        if (loginUser != null && PwdSaltUtils.verify(password, loginUser.getPassword())) {
            request.getSession(true).setAttribute(AppConstant.USER_SESSION_KEY, loginUser);    //将用户的会话对象保存到session会话域中
            System.out.println("登陆时的sessionId：" + request.getSession(false).getId());
            loginUser.setPassword(null);
            return HttpResult.success(loginUser);   //登陆成功就返回这个用户信息
        }
        return HttpResult.fail(-1, "账号或密码错误！");
    }


    @Value("${user_photos_path}")
    private String rootPath;
    @Value("${user_photo_relative_get_path}")
    private String relativeGetPath;

    @RequestMapping("/register")
    public HttpResult register(UserInfo userInfo, String captcha, HttpServletRequest request)
            throws ControllerException, MapperException {
        if (userInfo == null
                || !StringUtils.hasLength(userInfo.getUsername())
                || !StringUtils.hasLength(userInfo.getPassword())
                || !StringUtils.hasLength(userInfo.getNickname())) {
            throw new ControllerException("注册信息填写不完整！");
        }
        //检查验证码是否正确
        if (!MyCaptchaUtils.verifyCaptcha(request, captcha)) {
            return HttpResult.fail("验证码错误！");
        }
        try {
            userInfo.setPassword(PwdSaltUtils.encrypt(userInfo.getPassword())); //对用户密码加密
            userService.register(userInfo); //主键回显，返回了插入后用户的uid
            //将用户的会话对象放到session中，方便后边头像的上传
            request.getSession().setAttribute(AppConstant.USER_SESSION_KEY, userInfo);
        } catch (Exception e) {
            throw new MapperException("注册异常！用户名已存在！");
        }
        userInfo.setPassword(null);
        return HttpResult.success(userInfo); //注册成功就返回这个用户信息
    }

    /**
     * 返回验证码
     */
    @RequestMapping("/captcha")
    public void sendCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        MyCaptchaUtils.sendCaptcha(request, response);
    }

    @RequestMapping("/up_photo")
    public HttpResult uploadPhoto(@RequestPart("userPhoto") MultipartFile userPhoto, HttpServletRequest request) throws ControllerException {
        if (userPhoto.isEmpty()) {
            throw new ControllerException("头像未上传!");
        }
        //注册成功了，将头像信息保存到本地
        HttpSession session = request.getSession(false);
        UserInfo userInfo;
        if (session == null
                || (userInfo = (UserInfo) session.getAttribute(AppConstant.USER_SESSION_KEY)) == null) {
            throw new ControllerException("非法请求！");
        }
        String finalFileName;
        try {
            finalFileName = PhotoUtils.uploadPhoto(userPhoto, rootPath);
        } catch (IOException e) {
            throw new ControllerException("头像上传失败！请登陆后重新上传！");
        }
        //更新数据库中用户的头像信息
        userService.uploadPhoto(userInfo.getUId(), relativeGetPath + finalFileName);
        return HttpResult.success(200);
    }

    @RequestMapping("/info")
    public HttpResult getUserInfo(HttpServletRequest request) throws ControllerException {
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute(AppConstant.USER_SESSION_KEY) == null) {
            throw new ControllerException("非法请求！");
        }
        UserInfo userInfo = (UserInfo) session.getAttribute(AppConstant.USER_SESSION_KEY);
        userInfo.setPassword(null);
        return HttpResult.success(userInfo);
    }

    @RequestMapping("/get_users")
    public HttpResult getUsers(String username, HttpServletRequest request) throws ControllerException {
        if (!StringUtils.hasLength(username)) {
            throw new ControllerException("非法参数！");
        }
        HttpSession session = request.getSession(false);
        UserInfo userInfo;
        if (session == null ||
                (userInfo = (UserInfo) session.getAttribute(AppConstant.USER_SESSION_KEY)) == null
                || userInfo.getUId() == null) {
            throw new ControllerException("非法参数！");
        }
        List<UserInfo> usersLikeName = userService.getUsersLikeName(username);
        //如果这个用户已经是用户的好友了，就不返回了。如果是用户自己，就显示已添加
        for (UserInfo userTemp : usersLikeName) {
            if (friendService.isFriend(userInfo.getUId(), userTemp.getUId()) || userTemp.getUId().equals(userInfo.getUId())) {
                userTemp.setIsAdded(1);
            }
        }
        return HttpResult.success(usersLikeName);
    }


}
